﻿/// <reference path="jquery-1.8.2.js"/>

(function ($) {

	var settings;

	var methods = {
	    init: function (options) {

	        settings = {
	            'serviceUrl': '',
	            'employeeSip': '',
	            'employeeName': '',
	            'userName': '',
	            'session': '',
	            'onError': function () { },
	            'onMessageReceived': function () { },
	            'refreshRate': 2000,
	            'topic': '',
	            'showpage': 'true',
	            'isInInitialMode': 'false'
	        };

	        if (options) {
	            $.extend(settings, options);
	        }

	        //a lot of required options
	        if (settings.serviceUrl == "") $.error("You must declare a service URL!");
	        if (settings.employeeSip == "") $.error("You must declare an employeeSip!");
	        if (settings.employeeName == "") $.error("You must declare an employeeName!");
	        if (settings.userName == "") $.error("You must declare a userName!");
	        if (settings.session == "") $.error("You must declare a session!");

	        initChatSession(settings);


	        $("html").everyTime(settings.refreshRate, function () {
	            getMessagesFromServer(settings);
	        });

	        return this;

	    },
	    sendToServer: function (message) {
	        $.ajax({
	            type: 'GET',
	            url: settings.serviceUrl + 'SendInstantMessage?session=' + settings.session + '&message=' + message + '&r=' + Math.random(),
	            dataType: 'jsonp',
	            success: function (chatServiceResponse) {
	                if (chatServiceResponse.HasError == "true") {
	                    var errorCode = chatServiceResponse.ErrorCode;
	                    var errorMessage = chatServiceResponse.ErrorMessage;
	                    var isFatal = errorCode == "SessionError";
	                    settings.onError.call(this, errorMessage, isFatal);

	                    if (isFatal) disposeTimer();
	                }
	            },
	            error: function (xhr, ajaxOptions, thrownError) {
	                settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
	            }
	        });
	    },
	    dispose: function () {
	        disposeTimer();
	    },
	    getMessages: function () {
	        getMessagesFromServer(settings);
	    }
	};

	$.chat = function (method) {

		// Method calling logic
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.tooltip');
		}
	};

	var resizeTimerID = null;
	$(window).bind('resize', function () {
		if (resizeTimerID) clearTimeout(resizeTimerID);
		resizeTimerID = setTimeout(resizeChat, 100);
	});
	setTimeout(resizeChat, 100);
})(jQuery);

function disposeTimer() {
    $("html").stopTime();
}

function initChatSession(settings) {

    var pageParameter = "";

    if (settings.showpage == "true") {

        var url = window.opener.location.href;
        var title = '';

        $.get(url, function (response) {
            if (((/<title>(.*?)<\/title>/m).exec(response)) != null) {
                title = (/<title>(.*?)<\/title>/m).exec(response)[1];
            }

            pageParameter = "&page=" + url + "&title=" + title;
            serviceInitChatSession(settings, pageParameter);
        });

    } else {
        serviceInitChatSession(settings, pageParameter);
    }
}


function serviceInitChatSession(settings, pageParameter) {

    var serviceUrl = settings.serviceUrl + 'InitChatSession?session=' + settings.session + '&employeeSip=' + settings.employeeSip + '&username=' + settings.userName + pageParameter + '&topic=' + settings.topic + '&r=' + Math.random();
    
    $.ajax({
        type: 'GET',
        url: serviceUrl,
        dataType: 'jsonp',
        success: function (chatServiceResponse) {
            if (chatServiceResponse.HasError == "true") {
                var errorCode = chatServiceResponse.ErrorCode;
                var errorMessage = chatServiceResponse.ErrorMessage;
                settings.onError.call(this, errorMessage, errorCode == "SessionError");
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
        }
    });
}

function getMessagesFromServer(settings) {
    $.ajax({
        type: 'GET',
        url: settings.serviceUrl + 'GetMessages?session=' + settings.session + '&r=' + Math.random(),
        dataType: 'jsonp',
        success: function (instantMessageContainer) {
            $.each(instantMessageContainer.Messages, function (index, message) {
                settings.onMessageReceived.call(this, message.Value, message.Type);
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            settings.onError.call(this, 'Ajax error :' + ajaxOptions + ' / ' + thrownError, true);
            disposeTimer();
        }
    });

}

var minWidth = 320;
var minHeight = 260;
function resizeChat() {

	var width = $(window).width();
	var height = $(window).height();

	if (width > minWidth) {
		$(".presenceitem").width(width - 18);
		$("#chatWindowBody").width(width - 10);
		$("#conversation").width(width - 25);
		$("#typeMessageContainer").width(width - 10);
		$("#message").width(width - 16);
		$("#lastMessageReceived").width(width - 16);
		$(".presenceitem .buttons").width(width - 18);
	}
	if (height > minHeight) {
		$("#chatWindowBody").height(height - $(".presenceitem").height() - 30);
		$("#conversation").height($("#chatWindowBody").height() - 110);
		$("#typeMessageContainer").offset({ top: (height - $("#typeMessageContainer").height() - 10) });
		$("#lastMessageReceived").offset({ top: ($("#chatWindowBody").height() + 10) });
	}
}